import { ref, computed, nextTick } from 'vue';
import type { Ref } from 'vue';

export const useScrollView = (isGet:Ref<boolean>,prev:Function,next:Function) => {
	const scrollViewRef = ref();
	const handlePullDownRefresh = () => {
		nextTick(() => {
			scrollViewRef.value?.endRefresh?.();
			prev();
		});
	};
	const watchTouchmove = ref(false)
	const hasNext = ref(false);
	const hasFullPage = ref(true)
	const nextText = computed(() => (isGet.value||!hasFullPage.value ? undefined : hasNext.value ? 'tabbar.classifyRefresherTxt4' : 'tabbar.classifyRefresherTxt3'));
	
	let startTouchY = 0;
	const scrollHeight = ref(0)
	const handleScroll = (e: { detail: { scrollTop: number; scrollHeight: number }}) => {
		if (!isGet.value&&hasFullPage.value) {
			watchTouchmove.value = (e.detail.scrollHeight - e.detail.scrollTop) <= (scrollHeight.value+10)
			if(!watchTouchmove.value&&hasNext.value){
				hasNext.value = false
			}
		}
	}
	const handleTouchstart = (e: { touchX: number; touchY: number }) => {
		if (!isGet.value) {
			startTouchY = e.touchY;
		}
	};
	const handleTouchmove = (e: { touchX: number; touchY: number }) => {
		if (startTouchY && startTouchY > e.touchY) {
			hasNext.value = startTouchY - e.touchY > 120;
		}
	};
	
	const handleTouchend = (e: { touchX: number; touchY: number }) => {
		if (startTouchY) {
			if (startTouchY - e.touchY > 120) {
				next();
			}
		}
		startTouchY = 0;
		hasNext.value = false
	};
	
	const hasLoading = ref(true)
	
	
	return {
		scrollViewRef,
		handlePullDownRefresh,
		watchTouchmove,
		hasNext,
		hasFullPage,
		nextText,
		scrollHeight,
		handleScroll,
		handleTouchstart,
		handleTouchmove,
		handleTouchend,
		hasLoading
	}
}